<template>
    <div class="p-2">
        <transition>
            <div v-show="showSearch" class="mb-[10px]">
                <el-card shadow="hover">
                    <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                        <el-form-item label="租户编号" prop="tenantId">
                            <el-input v-model="queryParams.tenantId" placeholder="请输入租户编号" clearable
                                @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item label="联系人" prop="contactUserName">
                            <el-input v-model="queryParams.contactUserName" placeholder="请输入联系人" clearable
                                @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item label="联系电话" prop="contactPhone">
                            <el-input v-model="queryParams.contactPhone" placeholder="请输入联系电话" clearable
                                @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item label="企业名称" prop="companyName">
                            <el-input v-model="queryParams.companyName" placeholder="请输入企业名称" clearable
                                @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </div>
        </transition>

        <el-card shadow="hover">
            <template #header>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button v-hasPermi="['system:tenant:add']" type="primary" plain icon="Plus"
                            @click="handleAdd">新增</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button v-hasPermi="['system:tenant:edit']" type="success" plain icon="Edit"
                            :disabled="single" @click="handleUpdate">修改</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button v-hasPermi="['system:tenant:remove']" type="danger" plain icon="Delete"
                            :disabled="multiple" @click="handleDelete">删除</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button v-hasPermi="['system:tenant:export']" type="warning" plain icon="Download"
                            @click="handleExport">导出</el-button>
                    </el-col>
                    <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
                </el-row>
            </template>

            <el-table v-loading="loading" :data="tenantList" @selection-change="handleSelectionChange" height="650">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column v-if="false" label="id" align="center" prop="id" />
                <el-table-column label="租户编号" align="center" prop="tenantId" />
                <el-table-column label="联系人" align="center" prop="contactUserName" />
                <el-table-column label="联系电话" align="center" prop="contactPhone" />
                <el-table-column label="企业名称" align="center" prop="companyName" />
                <el-table-column label="社会信用代码" align="center" prop="licenseNumber" />
                <el-table-column label="过期时间" align="center" prop="expireTime" width="180">
                    <template #default="scope">
                        <span>{{ parseTime(scope.row.expireTime, '{y}-{m}-{d}') }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="租户状态" align="center" prop="status">
                    <template #default="scope">
                        <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
                            @change="handleStatusChange(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column width="250" label="操作" align="center" fixed="right"
                    class-name="small-padding fixed-width">
                    <template #default="scope">
                        <el-button v-hasPermi="['system:tenant:edit']" link type="text" icon="Edit"
                            @click="handleUpdate(scope.row)">编辑</el-button>
                        <el-button v-hasPermi="['system:tenant:edit']" link type="text" icon="Refresh"
                            @click="handleSyncTenantPackage(scope.row)">
                            同步套餐
                        </el-button>
                        <el-button v-hasPermi="['system:tenant:remove']" link type="text" icon="Delete"
                            @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
                :total="total" @pagination="getList" />
        </el-card>

        <!-- 添加或修改租户对话框 -->
        <el-dialog :visible.sync="dialog.visible" :title="dialog.title" width="35%" append-to-body>
            <el-form ref="tenantFormRef" :model="form" :rules="rules" label-width="130px" :inline="true">
                <el-form-item label="企业名称" prop="companyName">
                    <el-input v-model="form.companyName" placeholder="请输入企业名称" />
                </el-form-item>
                <el-form-item label="联系人" prop="contactUserName">
                    <el-input v-model="form.contactUserName" placeholder="请输入联系人" />
                </el-form-item>
                <el-form-item label="联系电话" prop="contactPhone">
                    <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
                </el-form-item>
                <el-form-item v-if="!form.id" label="用户名" prop="username">
                    <el-input v-model="form.username" placeholder="请输入系统用户名" maxlength="30" />
                </el-form-item>
                <el-form-item v-if="!form.id" label="用户密码" prop="password">
                    <el-input v-model="form.password" type="password" placeholder="请输入系统用户密码" maxlength="20" />
                </el-form-item>
                <el-form-item label="租户套餐" prop="packageId">
                    <el-select v-model="form.packageId" :disabled="!!form.tenantId" placeholder="请选择租户套餐" clearable
                        style="width: 100%">
                        <el-option v-for="item in packageList" :key="item.packageId" :label="item.packageName"
                            :value="item.packageId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="过期时间" prop="expireTime">
                    <el-date-picker v-model="form.expireTime" clearable type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择过期时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="用户数量" prop="accountCount">
                    <el-input v-model="form.accountCount" placeholder="请输入用户数量" />
                </el-form-item>
                <el-form-item label="绑定域名" prop="domain">
                    <el-input v-model="form.domain" placeholder="请输入绑定域名" />
                </el-form-item>
                <el-form-item label="企业地址" prop="address">
                    <el-input v-model="form.address" placeholder="请输入企业地址" />
                </el-form-item>
                <el-form-item label="企业代码" prop="licenseNumber">
                    <el-input v-model="form.licenseNumber" placeholder="请输入统一社会信用代码" />
                </el-form-item>
                <el-form-item label="企业简介" prop="intro">
                    <el-input v-model="form.intro" type="textarea" placeholder="请输入企业简介" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" placeholder="请输入备注" />
                </el-form-item>
                <el-form-item label="附件空间（MB）" prop="remark">
                    <el-input v-model="form.fileSize" placeholder="请输入附件空间（MB）" />
                </el-form-item>
                <el-form-item label="企业Logo">
                    <el-upload class="avatar-uploader" :action="url" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { listTenant, getTenant, delTenant, addTenant, updateTenant, changeTenantStatus, syncTenantPackage } from '@/api/system/tenant';
import { selectTenantPackage } from '@/api/system/tenantPackage';
import { getToken } from "@/utils/auth";
export default {
    data() {
        return {
            url: process.env.VUE_APP_BASE_API + '/iot/upload',
            header: {
                Authorization: 'Bearer ' + getToken(),
                clientid: process.env.VUE_APP_CLIENT_ID
            },
            imageUrl: "",
            tenantList: [],
            packageList: [],
            buttonLoading: false,
            loading: true,
            showSearch: true,
            ids: [],
            single: true,
            multiple: true,
            total: 0,
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                tenantId: '',
                contactUserName: '',
                contactPhone: '',
                companyName: ''
            },
            objectDetail: {},
            form: {
                id: undefined,
                tenantId: undefined,
                contactUserName: '',
                contactPhone: '',
                username: '',
                password: '',
                companyName: '',
                licenseNumber: '',
                domain: '',
                address: '',
                intro: '',
                remark: '',
                packageId: '',
                expireTime: '',
                accountCount: 0,
                status: '0',
                logo: "",
                fileSize: 0
            },
            rules: {
                id: [{ required: true, message: 'id不能为空', trigger: 'blur' }],
                tenantId: [{ required: true, message: '租户编号不能为空', trigger: 'blur' }],
                contactUserName: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
                contactPhone: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
                companyName: [{ required: true, message: '企业名称不能为空', trigger: 'blur' }],
                username: [
                    { required: true, message: '用户名不能为空', trigger: 'blur' },
                    { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '密码不能为空', trigger: 'blur' },
                    { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
                ]
            },
            dialog: {
                visible: false,
                title: ''
            }
        };
    },
    methods: {
        getTenantPackage() {
            selectTenantPackage().then((res) => {
                this.packageList = res.data
            });;
        },
        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
            this.form.logo =  res.data.url
        },
        beforeAvatarUpload(file) {
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isLt2M;
        },
        async getList() {
            this.loading = true;
            const res = await listTenant(this.queryParams);
            this.tenantList = res.rows;
            this.total = res.total;
            this.loading = false;
        },
        async handleStatusChange(row) {
            const text = row.status === '0' ? '启用' : '停用';
            try {
                await this.$confirm('确认要"' + text + '""' + row.companyName + '"租户吗？');
                await changeTenantStatus(row.id, row.tenantId, row.status);
                this.$message.success(text + '成功');
            } catch {
                row.status = row.status === '0' ? '1' : '0';
            }
        },
        cancel() {
            this.reset();
            this.dialog.visible = false;
        },
        reset() {
            this.form = {
                id: undefined,
                tenantId: undefined,
                contactUserName: '',
                contactPhone: '',
                username: '',
                password: '',
                companyName: '',
                licenseNumber: '',
                domain: '',
                address: '',
                intro: '',
                remark: '',
                packageId: '',
                expireTime: '',
                accountCount: 0,
                status: '0',
                logo: "",
                fileSize: 0
            };
            this.$refs.tenantFormRef.resetFields();
        },
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        resetQuery() {
            this.$refs.tenantFormRef.resetFields();
            this.handleQuery();
        },
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id);
            this.single = selection.length !== 1;
            this.multiple = selection.length === 0;
        },
        handleAdd() {
            this.dialog.visible = true;
            this.dialog.title = '添加租户';
            this.reset();
            this.getTenantPackage();
        },
        handleUpdate(row) {
            this.dialog.visible = true;
            this.dialog.title = '修改租户';
            this.getTenantPackage();
            const _id = row?.id || this.ids[0];
            getTenant(_id).then((res) => {
                this.reset()
                this.objectDetail = res;
                this.imageUrl = this.objectDetail.data.logo
                Object.assign(this.form, this.objectDetail.data);
            });
        },
        async submitForm() {
            this.$refs.tenantFormRef.validate(async (valid) => {
                if (valid) {
                    this.buttonLoading = true;
                    if (this.form.id) {
                        await updateTenant(this.form).finally(() => this.buttonLoading = false);
                    } else {
                        await addTenant(this.form).finally(() => this.buttonLoading = false);
                    }
                    this.$message.success('操作成功');
                    this.dialog.visible = false;
                    await this.getList();
                }
            });
        },
        async handleDelete(row) {
            const _ids = row?.id || this.ids;
            await this.$confirm('是否确认删除租户编号为"' + _ids + '"的数据项？');
            this.loading = true;
            await delTenant(_ids).finally(() => this.loading = false);
            await this.getList();
            this.$message.success('删除成功');
        },
        async handleSyncTenantPackage(row) {
            try {
                await this.$confirm('是否确认同步租户套餐租户编号为"' + row.tenantId + '"的数据项？');
                this.loading = true;
                await syncTenantPackage(row.tenantId, row.packageId);
                await this.getList();
                this.$message.success('同步成功');
            } catch {
                return;
            } finally {
                this.loading = false;
            }
        },
        handleExport() {
            this.download(
                'system/tenant/export',
                { ...this.queryParams },
                `tenant_${new Date().getTime()}.xlsx`
            );
        }
    },
    mounted() {
        this.getList();
    }
};
</script>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>